﻿(function () {

    // Declare global configurations
    $.configGlobal = {
        // Uri api fields
        uriGetMotelsAPI: "http://localhost:1790/motelmaps/all_address",
        urtGetWardsAPI: "http://localhost:1790/motelmaps/all_wards/{0}",
        urtGetDistrictsAPI: "http://localhost:1790/motelmaps/all_districts",
        urlGetResultSearchAPI: "http://localhost:1790/motelmaps/re_search/{0}/{1}",
        urlDeleteMotelsAPI: "http://localhost:1790/motelmaps/delete_address/{0}",
        // Protocol call
        protoGET: "GET",
        protoPOST: "POST",
        protoDELETE: "DELETE",
        protoPUT: "PUT",
        // Expected datatype
        dataJSON: "json",
        // ContentType
        ctnJSON: "application/json; charset=utf-8",
        // Html fields
        divContainMap: "map_canvas",
        cbWardSearch: "#cbWardSearchAddress",
        cbWardAdd: "#cbWardAddress",
        cbDistrictSearch: "#cbDistrictSearchAddress",
        cbDistrictAdd: "#cbDistrictAddress",
        btnSearch: "#btnsearch",
        btnSave: "#btnSave",
        btnCancel: "#btnCancel",
        msgAddResponse: "#msgAddAddress",
        btnShowAllMotels: "#btnShow",
        // Variabel fields
        infoWindow: new google.maps.InfoWindow(),
        visibleStatus: 1,
        disableStatus: 0,
        mapDiv: "",
        mapObject: "",
        defaultLocaltion: new google.maps.LatLng(10.7633174, 106.6823476),
        defaultZoom: 13,
        defaultScaleControl: true,
        districts: "",
        wardsSearch: "",
        wardsAdd: "",
        motels: "",
        addsSearch: ""
    };

    // Declare event for add button
    $('.fancybox').fancybox();

    // Declare function to implement onload event for map
    window.onload = function () {
        // Get map div place holders
        $.configGlobal.mapDiv = document.getElementById($.configGlobal.divContainMap);
        // Declare implement event for btnSave in add form
        $($.configGlobal.btnSave).click(btnSaveOnClick);
        // Get ward comboboxes
        //getWardComboBoxes();
        getDistrictsComboBoxes();
        // Add selected index changing to 
        $($.configGlobal.cbDistrictAdd).change(cbDistrictAddSelectedIndexChanging);
        $($.configGlobal.cbDistrictSearch).change(cbDistrictSearchSelectedIndexChanging);
        // Add even to info window
        google.maps.event.addListener($.configGlobal.infoWindow, 'domready', function () {
            // whatever you want to do once the DOM is ready
            $('#delMarker').click(markerDeleteOnClick);
            $('#upMarker').click(markerUpdateOnClick);
        });
        // Search
        $($.configGlobal.btnSearch).click(btnSearchClick);
        // Call motel api
        $($.configGlobal.btnShowAllMotels).click(btnShowAllOnClick);
        getAllMotels();
    }

    function markerUpdateOnClick() {
        // Get selected motel
        var selectedId = $(this).attr('title');
        // Confirm user
        var userAction = confirm("Do you want update motel {0} ?".format(selectedId));
        // If user confirm not update
        if (userAction == false) {
            return;
        }
        var divTableParent = $(this).parent().parent().parent();
        var latVal = divTableParent.find('#txtLat').val();
        var logVal = divTableParent.find('#txtLog').val();
        //        console.log("lat: {0} - long:{1}".format(latVal, logVal));        
        // Prepare object to send
        var addressData = {
            MaDiaChi: selectedId,
            KinhDo: logVal,
            ViDo: latVal
        };
        // Call api and waiting response
        $.ajax({
            url: $.configGlobal.uriGetMotelsAPI,
            type: $.configGlobal.protoPUT,
            dataType: $.configGlobal.dataJSON,
            contentType: $.configGlobal.ctnJSON,
            data: JSON.stringify(addressData),
            cache: false,
            async: false,
            success: function (response) {
                if (response == null) {
                    console.log("returned data from update address api is empty !");
                    return;
                }
                console.log(response);
                // Reload map
                getAllMotels();
            },
            error: function (request, status, msg) {
                console.log(msg);
            }
        });
    }

    function markerDeleteOnClick() {
        // Get selected motel
        var selectedId = $(this).attr('title');
        // Confirm user
        var userAction = confirm("Do you want delete motel {0} ?".format(selectedId));
        // If user confirm not delete
        if (userAction == false) {
            return;
        }
        // Call api       
        $.ajax({
            url: $.configGlobal.urlDeleteMotelsAPI.format(selectedId),
            type: $.configGlobal.protoDELETE,
            dataType: $.configGlobal.dataJSON,
            contentType: $.configGlobal.ctnJSON,
            success: function (data) {
                if (data == null) {
                    console.log("returned data from delete motel api is empty !");
                    return;
                }
                console.log(data);
                getAllMotels();
            },
            error: function (request, status, msg) {
                console.log(msg);
            }
        });
        return false;
    }

    function btnShowAllOnClick() {
        getAllMotels();
        return false;
    }

    function btnSaveOnClick() {
        // Get all information of saving address
        var soNha = $('#txtNumAddress').val();
        var tenDuong = $('#txtRoadAddress').val();
        var quan = $('#cbDistrictAddress').val();
        var phuong = $('#cbWardAddress').val();
        var viDo = $('#txtLatAddress').val();
        var kinhDo = $('#txtLogAddress').val();
        var tinhTrang = $.configGlobal.visibleStatus;
        // Prepare object to send
        var addressData = {
            SoNha: soNha,
            TenDuong: tenDuong,
            MaPhuong: phuong,
            MaQuan: quan,
            TinhTrang: tinhTrang,
            KinhDo: kinhDo,
            ViDo: viDo
        };
        // Call api and waiting response
        $.ajax({
            url: $.configGlobal.uriGetMotelsAPI,
            type: $.configGlobal.protoPOST,
            dataType: $.configGlobal.dataJSON,
            contentType: $.configGlobal.ctnJSON,
            data: JSON.stringify(addressData),
            cache: false,
            async: false,
            success: function (response) {
                if (response == null) {
                    console.log("returned data from insert new address api is empty !");
                    return;
                }
                $($.configGlobal.msgAddResponse).html(response);
                // Reload map
                getAllMotels();
            },
            error: function (request, status, msg) {
                console.log(msg);
            }
        });
    }

    function clearOptionFromComboBox(objComboBox) {
        var tempComboBox = objComboBox;
        var countOptions = tempComboBox.find('option').length;
        // None clear if comboBox empty
        if (countOptions < 1) {
            return;
        }
        // Clear options in comboBox
        tempComboBox
			.find('option')
			.remove()
			.end();
    }

    function cbDistrictAddSelectedIndexChanging() {
        var selectedDistrict = $($.configGlobal.cbDistrictAdd).val();
        // Call ajax to motel api
        $.ajax({
            url: $.configGlobal.urtGetWardsAPI.format(selectedDistrict),
            type: $.configGlobal.protoGET,
            dataType: $.configGlobal.dataJSON,
            contentType: $.configGlobal.ctnJSON,
            success: function (data) {
                if (data == null) {
                    console.log("returned data from ward add api is empty !");
                    return;
                }
                // Assign list motels to global
                $.configGlobal.wardsAdd = data;
                console.log("call ward add api success");
                // Binding comboBoxes
                loadWardsToAddComboBox();
            },
            error: function (request, status, msg) {
                console.log(msg);
            }
        });
    }

    function cbDistrictSearchSelectedIndexChanging() {
        var selectedDistrict = $($.configGlobal.cbDistrictSearch).val();
        // Call ajax to motel api
        $.ajax({
            url: $.configGlobal.urtGetWardsAPI.format(selectedDistrict),
            type: $.configGlobal.protoGET,
            dataType: $.configGlobal.dataJSON,
            contentType: $.configGlobal.ctnJSON,
            success: function (data) {
                if (data == null) {
                    console.log("returned data from ward search api is empty !");
                    return;
                }
                // Assign list motels to global
                $.configGlobal.wardsSearch = data;
                console.log("call ward search api success");
                // Binding comboBoxes
                loadWardsToSearchComboBox();
            },
            error: function (request, status, msg) {
                console.log(msg);
            }
        });
    }

    function loadDistrictsToComboBoxes() {
        var tempDistricts = $.configGlobal.districts;
        // Check type of motels global is none array
        if (!(tempDistricts instanceof Array)) {
            console.log("districts variable none array types");
            return;
        }
        console.log("districts variable is array types");
        var tempSizeOfDistricts = tempDistricts.length;
        if (tempSizeOfDistricts < 1) {
            console.log("districts variable is empty");
            return;
        }
        console.log("length of districts is {0}".format(tempSizeOfDistricts));
        // Get combobox  add form
        var tempDistrictAddCombo = $($.configGlobal.cbDistrictAdd);
        var tempDistrictSearchCombo = $($.configGlobal.cbDistrictSearch);
        // Each item in ward 
        for (var i = 0; i < tempSizeOfDistricts; i++) {
            var tempDistrict = tempDistricts[i];
            tempDistrictAddCombo.append("<option value='{0}'>{1}</option>".format(tempDistrict.MaQuan, tempDistrict.TenQuan));
            tempDistrictSearchCombo.append("<option value='{0}'>{1}</option>".format(tempDistrict.MaQuan, tempDistrict.TenQuan));
            tempDistrict = null;
        }
    }

    // Declare function to binding ward to combobox add form
    function getDistrictsComboBoxes() {
        // Call ajax to motel api
        $.ajax({
            url: $.configGlobal.urtGetDistrictsAPI,
            type: $.configGlobal.protoGET,
            dataType: $.configGlobal.dataJSON,
            contentType: $.configGlobal.ctnJSON,
            success: function (data) {
                if (data == null) {
                    console.log("returned data from districts api is empty !");
                    return;
                }
                // Assign list motels to global
                $.configGlobal.districts = data;
                console.log("call districts api success");
                // Binding comboBoxes
                loadDistrictsToComboBoxes();
            },
            error: function (request, status, msg) {
                console.log(msg);
            }
        });
    }

    // Declare function to load ward to comboBoxes
    function loadWardsToSearchComboBox() {
        var tempWards = $.configGlobal.wardsSearch;
        // Check type of motels global is none array
        if (!(tempWards instanceof Array)) {
            console.log("wards search variable none array types");
            return;
        }
        console.log("wards search variable is array types");
        var tempSizeOfWards = tempWards.length;
        // Get combobox  search form        
        var tempWardSearchCombo = $($.configGlobal.cbWardSearch);
        clearOptionFromComboBox(tempWardSearchCombo);
        if (tempSizeOfWards < 1) {
            console.log("wards search variable is empty");
            return;
        }
        console.log("length of wards search is {0}".format(tempSizeOfWards));
        // Each item in ward 
        for (var i = 0; i < tempSizeOfWards; i++) {
            var tempWard = tempWards[i];
            tempWardSearchCombo.append("<option value='{0}'>{1}</option>".format(tempWard.MaPhuong, tempWard.TenPhuong));
            tempWard = null;
        }
    }

    // Declare function to load ward to comboBoxes
    function loadWardsToAddComboBox() {
        var tempWards = $.configGlobal.wardsAdd;
        // Check type of motels global is none array
        if (!(tempWards instanceof Array)) {
            console.log("wards add variable none array types");
            return;
        }
        console.log("wards add variable is array types");
        var tempSizeOfWards = tempWards.length;
        // Get combobox  add form
        var tempWardAddCombo = $($.configGlobal.cbWardAdd);
        clearOptionFromComboBox(tempWardAddCombo);
        if (tempSizeOfWards < 1) {
            console.log("wards variable is empty");
            return;
        }
        console.log("length of wards is {0}".format(tempSizeOfWards));
        // Each item in ward 
        for (var i = 0; i < tempSizeOfWards; i++) {
            var tempWard = tempWards[i];
            tempWardAddCombo.append("<option value='{0}'>{1}</option>".format(tempWard.MaPhuong, tempWard.TenPhuong));
            tempWard = null;
        }
    }

    function createMarker(point, content) {
        var tempPoint = point;
        var tempContent = content;
        var tempMap = $.configGlobal.mapObject;
        var itemMarker = new google.maps.Marker({
            position: tempPoint,
            map: tempMap
        });
        google.maps.event.addListener(itemMarker, 'click', function () {
            $.configGlobal.infoWindow.setContent(tempContent);
            // Show detail info window
            $.configGlobal.infoWindow.open(tempMap, itemMarker);
        });
    }

    // Declare function to generate markers to map
    function generateMarkers(arrayMotels) {
        var arrayResult = [];
        var tempMotels = arrayMotels;
        var tempMap = $.configGlobal.mapObject;
        if (tempMap instanceof String || tempMap == null) {
            console.log("map object params is invalid");
            return arrayResult;
        }
        if (!(tempMotels instanceof Array)) {
            console.log("motels param none array types");
            return arrayResult;
        }
        var tempSizeOfMotels = tempMotels.length;
        if (tempSizeOfMotels < 1) {
            console.log("motels param is empty");
            return arrayResult;
        }
        // Each item in temp array motel
        for (var i = 0; i < tempSizeOfMotels; i++) {
            var tempLocation = tempMotels[i];
            var tempPoint = new google.maps.LatLng(tempLocation.KinhDo, tempLocation.ViDo);
            var contentInfoWindow = $('.info').html();
            var test = tempLocation.SoNha + " " + tempLocation.TenDuong;
            contentInfoWindow = contentInfoWindow.format(test, tempLocation.KinhDo,
                                                                                   tempLocation.ViDo, tempLocation.MaDiaChi,
                                                                                   tempLocation.MaDiaChi);
            var itemMarker = createMarker(tempPoint, contentInfoWindow);
            arrayResult.push(itemMarker);
            tempLocation = null;
        }
    }

    // Declare function to load maps with motels
    function loadMotelsToMap() {
        var tempMotels = $.configGlobal.motels;
        // Check type of motels global is none array
        if (!(tempMotels instanceof Array)) {
            console.log("motels variable none array types");
            return;
        }
        console.log("motels variable is array types");
        var tempSizeOfMotels = tempMotels.length;
        if (tempSizeOfMotels < 1) {
            console.log("motels variable is empty");
            return;
        }
        console.log("length of motels is {0}".format(tempSizeOfMotels));
        // Get default location
        var tempDefaultLocation = $.configGlobal.defaultLocaltion;
        var tempDefaultZoom = $.configGlobal.defaultZoom;
        var tempDefaultScaleControl = $.configGlobal.defaultScaleControl;
        var tempMapDiv = $.configGlobal.mapDiv;
        // Init object menu
        var menu = new Menu(tempMapDiv),
             currentPointer,
             center = [10.76356, 106.682351];
        // MENU : ITEM 1
        menu.add('Submenu 01', 'itemB',
        function () {
            menu.close();
            addMarker(false);
        })
        // MENU : ITEM 2
        menu.add('Submenu 02', 'itemA separator',
        function () {
            menu.close();
            addMarker(true);
        })
        // Load map options
        var options = {
            center: tempDefaultLocation,
            zoom: tempDefaultZoom,
            scaleControl: tempDefaultScaleControl,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        // Load maps
        var tempMap = new google.maps.Map(tempMapDiv, options);
        $.configGlobal.mapObject = tempMap;
        // Init events for maps
        google.maps.event.addListener($.configGlobal.mapObject, 'rightclick', function (event) {
            currentPointer = event;
            menu.open(currentPointer);
        });
        google.maps.event.addListener($.configGlobal.mapObject, 'click', function () {
            menu.close();
        });
        google.maps.event.addListener($.configGlobal.mapObject, 'dragstart', function () {
            menu.close();
        });
        google.maps.event.addListener($.configGlobal.mapObject, 'zoom_changed', function () {
            menu.close();
        });
        // Generate all markers from item in motels
        var markers = generateMarkers(tempMotels);
        // Binding marker to map
    }

    // Declare function to get all location from motel services
    function getAllMotels() {
        // Call ajax to motel api
        $.ajax({
            url: $.configGlobal.uriGetMotelsAPI,
            type: $.configGlobal.protoGET,
            dataType: $.configGlobal.dataJSON,
            contentType: $.configGlobal.ctnJSON,
            success: function (data) {
                if (data == null) {
                    console.log("returned data from motel api is empty !");
                    return;
                }
                // Assign list motels to global
                $.configGlobal.motels = data;
                console.log("call motel api success");
                // Generate map
                loadMotelsToMap();
            },
            error: function (msg, url, line) {
                console.log(msg);
            }
        });
    }

    // Search with District and Ward
    function btnSearchClick() {
        var selectedDistrict = $($.configGlobal.cbDistrictSearch).val();
        var selecetedWard = $($.configGlobal.cbWardSearch).val();
        // Call ajax to motel api
        $.ajax({
            url: $.configGlobal.urlGetResultSearchAPI.format(selectedDistrict, selecetedWard),
            type: $.configGlobal.protoGET,
            dataType: $.configGlobal.dataJSON,
            contentType: $.configGlobal.ctnJSON,
            success: function (data) {
                if (data == null) {
                    console.log("returned data from ward search api is empty !");
                    return;
                }
                //Assign list motels to global
                $.configGlobal.addsSearch = data;
                console.log("call ward search api success");
                // Call
                loadMotelsResultSearchToMap();
            },
            error: function (request, status, msg) {
                console.log(msg);
            }
        });
    }

    // Declare function to load maps with result search motels 
    function loadMotelsResultSearchToMap() {
        var tempMotels = $.configGlobal.addsSearch;
        // Check type of motels global is none array
        if (!(tempMotels instanceof Array)) {
            console.log("motels variable none array types");
            return;
        }
        console.log("motels variable is array types");
        var tempSizeOfMotels = tempMotels.length;
        if (tempSizeOfMotels < 1) {
            console.log("motels variable is empty");
            $.msgBox({
                title: "Motel Maps",
                content: "Không tìm thấy nhà trọ nào trong khu vực này !!"
            });
            return;
        }
        console.log("length of motels is {0}".format(tempSizeOfMotels));
        // Get default location
        var tempLocation = tempMotels[0];
        var tempDefaultLocation = new google.maps.LatLng(tempLocation.KinhDo, tempLocation.ViDo);
        var tempDefaultZoom = $.configGlobal.defaultZoom;
        var tempDefaultScaleControl = $.configGlobal.defaultScaleControl;
        var tempMapDiv = $.configGlobal.mapDiv;
        // Load map options
        var options = {
            center: tempDefaultLocation,
            zoom: tempDefaultZoom,
            scaleControl: tempDefaultScaleControl,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        // Load maps
        var tempMap = new google.maps.Map(tempMapDiv, options);
        $.configGlobal.mapObject = tempMap;
        // Generate all markers from item in motels
        var markers = generateMarkers(tempMotels);
    }

})();
